const express = require('express')
const router = express.Router()
const humps = require('humps')
const db = require('../../database/db')

module.exports = (() => {
    // 订单管理
    router.get('/records', async (req, res, next) => {
        try {
            let sql = '',
                time = ''
            req.query.sign === '未签订' ? sql += 'AND r.`is_sign` = 0 ' :
                req.query.sign === '已签订' ? sql += 'AND r.`is_sign` = 1 ' : sql += ''
            if (+req.query.depositToAchievement) {
                sql += 'AND r.`deposit_to_achievement` = 1 '
            } else {
                sql += 'AND r.`deposit_to_achievement` = 0 '
            }
            req.query.from ? time += 'AND r.`time` >= "' + req.query.from + '" AND r.`time` <= "' + req.query.to + '" ' : ''

            const doc = humps.camelizeKeys(await db.getRecords({ limit: req.query.limit, offset: req.query.offset, search: req.query.search, sql, time }))
            const { total } = await db.getRecordsTotal({ search: req.query.search, sql, time })
            const temp = []
            const promises = []
            doc.forEach(async item => {
                const promise = new Promise(async resolve => {
                    const notsign = item.notsign ? await db.getNotSignById(item.notsign) : '无'
                    const negotiator = item.negotiatorId ? await db.getNegotiatorById(item.negotiatorId) : '无'
                    item.notsign = notsign.name
                    item.negotiator = negotiator.name
                    temp.push(item)
                    resolve(temp)
                })
                promises.push(promise)

                item.isSign === 1 ? item.isSign = "已签订" : item.isSign = "未签订"
                item.isMortgage === 1 ? item.isMortgage = "按揭" : item.isMortgage = "全款"
                item.depositToAchievement ? item.depositToAchievement = true : item.depositToAchievement = false
            })
            Promise.all(promises).then((data) => {
                res.send({
                    doc,
                    total
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/addRecord', async (req, res, next) => {
        try {
            let existRecord = await db.getRecordByPhone(req.body.phone)
            if (existRecord) {
                res.json({
                    status: 0,
                    msg: '该订单已经存在！'
                })
                return
            }

            const promotion = await db.getPromotionByName(req.body.promotion)
            const center = await db.getCenterByName(req.body.center)
            const dept = await db.getDeptByName({ name: req.body.dept, center: req.body.center })
            const salesman = await db.getSalesmanByName({ name: req.body.salesman, dept: req.body.dept, center: req.body.center })
            const notsign = await db.getNotSignByName(req.body.notsigning)
            const distribution = await db.getDistributionByName(req.body.distribution)
            const negotiator = req.body.negotiator === '无' ? 0 : await db.getNegotiatorByName(req.body.negotiator)
            const data = {
                promotion_id: promotion.id,
                time: req.body.time,
                name: req.body.name,
                distribution_id: distribution.id,
                deposit: req.body.deposit,
                phone: req.body.phone,
                center_id: center.id,
                dept_id: dept.id,
                is_sign: req.body.is_sign === "已签订" ? 1 : 0,
                is_mortgage: req.body.is_mortgage === "按揭" ? 1 : 0,
                negotiator: negotiator ? negotiator.id : 0,
                salesman_id: salesman.id,
                notsign_id: notsign ? notsign.id : 0,
                deposit_to_achievement: req.body.depositToAchievement ? 1 : 0,
                charge: req.body.depositToAchievement ? req.body.deposit : 0,
            }
            const success = await db.addRecord(data)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.put('/editRecord/:id', async (req, res, next) => {
        try {
            let existRecord = await db.getRecordById(req.params.id)
            if (!existRecord) {
                res.json({
                    status: 0,
                    msg: '该订单不存在！'
                })
                return
            }

            const promotion = await db.getPromotionByName(req.body.promotion)
            const center = await db.getCenterByName(req.body.center)
            const dept = await db.getDeptByName({ name: req.body.dept, center: req.body.center })
            const salesman = await db.getSalesmanByName({ name: req.body.salesman, dept: req.body.dept, center: req.body.center })
            const notsign = req.body.notsigning === '无' ? '' : await db.getNotSignByName(req.body.notsigning)
            const distribution = await db.getDistributionByName(req.body.distribution)
            const negotiator = req.body.negotiator === '无' ? 0 : await db.getNegotiatorByName(req.body.negotiator)
            const data = {
                id: req.params.id,
                promotion_id: promotion.id,
                time: req.body.time,
                name: req.body.name,
                distribution_id: distribution.id,
                deposit: req.body.deposit,
                phone: req.body.phone,
                center_id: center.id,
                dept_id: dept.id,
                is_sign: req.body.is_sign === "已签订" ? 1 : 0,
                is_mortgage: req.body.is_mortgage === "按揭" ? 1 : 0,
                negotiator: negotiator ? negotiator.id : 0,
                salesman_id: salesman.id,
                notsign_id: notsign ? notsign.id : 0,
                deposit_to_achievement: req.body.depositToAchievement ? 1 : 0,
                charge: req.body.depositToAchievement ? req.body.deposit : 0,
            }
            const success = await db.updateRecord(data) // 更新订单表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeRecord/:id', async (req, res, next) => {
        try {
            let existRecord = await db.getRecordById(req.params.id)
            if (!existRecord) {
                res.json({
                    status: 0,
                    msg: '该订单不存在！'
                })
                return
            }

            const success = await db.rmRecordById(req.params.id)// 删除订单表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })
    // 计划管理

    router.get('/plans', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getPlans({ limit: req.query.limit, offset: req.query.offset, search: req.query.search }))
            const { total } = await db.getPlansTotal(req.query.search)
            res.send({
                doc,
                total
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/addPlan', async (req, res, next) => {
        try {
            let existPlan = await db.getPlanByTime({ time: req.body.time, center: req.body.center, department: req.body.department })
            if (existPlan) {
                res.json({
                    status: 0,
                    msg: '该计划已经存在！'
                })
                return
            }

            const center = await db.getCenterByName(req.body.center)
            const dept = await db.getDeptByName({ name: req.body.department, center: req.body.center })
            const data = {
                time: req.body.time,
                center_id: center.id,
                dept_id: dept.id,
                visit_plan: req.body.visit_plan,
                sign_plan: req.body.sign_plan
            }
            const success = await db.addPlan(data)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removePlan/:id', async (req, res, next) => {
        try {
            let existPlan = await db.getPlanById(req.params.id)
            if (!existPlan) {
                res.json({
                    status: 0,
                    msg: '该计划不存在！'
                })
                return
            }

            const success = await db.rmPlanById(req.params.id)// 删除计划表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    return router
})();